import {baseUrl} from '../api/index'

export const uploadFiles = (filesPath, url) => {
  return new Promise((resolve, reject) => {
    let uploadImgCount = 0
    let _resDataArr = []
    let _files = filesPath
    wx.showToast({
      title: '正在上传...',
      icon: 'loading',
      mask: true,
      duration: 60000
    })
    for (let i = 0, h = _files.length; i < h; i++) {
      wx.uploadFile({
        url: url || (baseUrl + '/api/article/upload_img'),
        filePath: _files[i],
        name: 'images',
        formData: {
          'imgIndex': i
        },
        header: {
          'Content-Type': 'multipart/form-data',
          'token': wx.getStorageSync('auth_token'),
          'position-x': wx.getStorageSync('user_location_x'),
          'position-y': wx.getStorageSync('user_location_y'),
        },
        success (res) {
          uploadImgCount++
          let data = JSON.parse(res.data)
          //如果是最后一张,则隐藏等待中
          if (data.status === 1) {
            _resDataArr[i] = data
          } else {
            wx.hideToast({
              complete () {
                wx.showToast({
                  icon: 'none',
                  title: data.info
                })
              }
            })
            reject(_resDataArr)
          }
          if (uploadImgCount === _files.length) {
            wx.hideToast()
            resolve(_resDataArr)
          }
        },
        fail (res) {
          wx.hideToast()
          wx.showModal({
            title: '错误提示',
            content: '上传失败',
            showCancel: false
          })
          reject(JSON.parse(res.data))
        }
      })
    }
  })
}